const { PrismaClient } = require('@prisma/client');

const prisma = new PrismaClient();

async function main() {
  const args = process.argv.slice(2);
  let excludeId = null;

  for (const arg of args) {
    if (arg.startsWith('--exclude=')) {
      const value = arg.split('=')[1];
      if (value) {
        try {
          excludeId = BigInt(value);
        } catch (err) {
          console.error('无法解析 exclude 参数为数字:', value);
          process.exit(1);
        }
      }
    }
  }

  console.log('📊 查询开启公众号推送的用户列表');
  if (excludeId !== null) {
    console.log('🔍 排除用户ID:', excludeId.toString());
  }

  try {
    const where = {
      wechat_official_subscribed: true,
      wechat_official_openid: { not: null },
      wechat_notification_enabled: true
    };

    if (excludeId !== null) {
      where.id = { not: excludeId };
    }

    const users = await prisma.users.findMany({
      where,
      select: {
        id: true,
        nickname: true,
        wechat_official_openid: true,
        wechat_official_subscribed: true,
        wechat_notification_enabled: true
      },
      orderBy: { id: 'asc' }
    });

    console.log(`✅ 共找到 ${users.length} 位用户`);
    users.forEach(user => {
      console.log(` - ID:${user.id.toString()} 昵称:${user.nickname || '未设置'} OpenID:${user.wechat_official_openid}`);
    });

    if (users.length === 0) {
      console.log('⚠️ 没有用户符合推送条件，请检查数据库字段');
    }
  } catch (error) {
    console.error('❌ 查询失败:', error);
  } finally {
    await prisma.$disconnect();
  }
}

main()
  .then(() => {
    process.exit(0);
  })
  .catch(error => {
    console.error('❌ 脚本异常退出:', error);
    process.exit(1);
  });
